package com.dongss.study.shiro;

import com.dongss.study.domain.User;
import com.dongss.study.service.RoleMenuAssignmentService;
import com.dongss.study.service.UserRoleAssignmentService;
import com.dongss.study.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by dongshuanshuan on 17-7-29.
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    UserService userService;

    @Resource
    UserRoleAssignmentService userRoleAssignmentService;

    @Resource
    RoleMenuAssignmentService roleMenuAssignmentService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo...");

        String loginName=(String)principalCollection.fromRealm(getName()).iterator().next();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Set<String> roles=userRoleAssignmentService.findRoleNamesByUsername(loginName);
        for(String str:roles){
            System.out.println("role:"+str);
        }
        info.setRoles(roles);

        Set<String> permissions=roleMenuAssignmentService.findPermissionsByUsername(loginName);
        for(String str:permissions){
            System.out.println("permissions:"+str);
        }
        info.setStringPermissions(permissions);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo...");
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;

        User user=userService.findByName(token.getUsername());
        if(user==null){
            throw new UnknownAccountException();
        }

        return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
    }
}
